package com.tool.xmltool.util;

import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 软算法
 * @author zhoubin
 * @date 2022/9/16 10:41
 */
@Slf4j
public class SecurityUtil {

    /**
     * MD5加密
     * 返回32位加密后的内容
     * 32位的加密: buf.toString()
     * 16位的加密: buf.toString().substring(8,24)
     * @param plainText
     * @return
     */
    public static String md5(String plainText) {

        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(plainText.getBytes(StandardCharsets.UTF_8));
            byte[] digest = md5.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < digest.length; offset++) {
                i = digest[offset];
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }

            return buf.toString().toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            log.error("md5加密失败:", e);
        }

        return null;
    }
}
